package leo.manager
{
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.utils.Dictionary;
	import flash.utils.getDefinitionByName;
	/**
	 * 音乐管理器 
	 * @author leo
	 * 
	 */
	public class SoundManager
	{
		private static var _instance :SoundManager = null;
		private var soundDict :Dictionary;
		public function SoundManager()
		{
			soundDict = new Dictionary();
		}
		
		public static function get instance():SoundManager
		{
			
			if(_instance == null)
			{
				_instance = new SoundManager();
			}
			return _instance;
		}
		
		/**
		 * 播放音乐 
		 * @param name
		 * @param loop
		 * 
		 */		
		public function play(name :String,loop :int = 1):void
		{
			try
			{
				for(var key : * in soundDict)
				{
					stop(key);
				}
				
				var ref :Class = getDefinitionByName(name) as Class;
				var sc :SoundChannel = (new ref() as Sound).play(0,(loop != -1) ? loop : int.MAX_VALUE);
				if(sc)
				{
					if(loop != 0 && loop != -1)
					{
						sc.addEventListener(Event.SOUND_COMPLETE,soundCompleteHandler);
					}
					soundDict[name] = sc;
				}
			}catch(e :Error)
			{
				
			}
		}
		/**
		 * 停止音乐 
		 * @param name
		 * 
		 */		
		public function stop(name :String):void
		{
			var sc :SoundChannel = soundDict[name];
			if(sc)
			{
				sc.stop();
			}
			delete soundDict[name];
		}
		/**
		 * 是否在播放 
		 * @param name
		 * @return 
		 * 
		 */		
		public function isPlaying(name :String):Boolean
		{
			return soundDict[name] != null;
		}
		
		private function soundCompleteHandler(event :Event):void
		{
			event.currentTarget.removeEventListener(Event.SOUND_COMPLETE,soundCompleteHandler);
			for(var key : * in soundDict)
			{
				if(soundDict[key] == event.currentTarget)
				{
					delete soundDict[key];
					return;
				}
			}
		}

	}
}